package com.mls.guardian.appst.chain.excutor;

import com.mls.guardian.appst.chain.TaskExecutor;
import com.mls.guardian.appst.chain.TaskInvoker;
import com.mls.guardian.appst.chain.TaskResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Iterator;

/**
 * Created by 2014-400 on 2015-10-26.
 */
public class ReplaceJsExcutor implements TaskExecutor {
    private static final Logger log = LoggerFactory.getLogger(ReplaceJsExcutor.class);

    @Override
    public TaskResult exec(TaskInvoker invoker) {
        String targetFolder = invoker.getConfig().getMoveDest() + File.separator + invoker.getProject().getProjectName();

        TaskResult result = new TaskResult();
        try {
            log.info("----开始replace js----");
            Iterator<String> iterator = invoker.getProject().getReplaceFileMap().keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();//全路径
                String value = invoker.getProject().getReplaceFileMap().get(key);//模块路径
                String targetFile = targetFolder + File.separator + value;

                //创建目录
                if (Files.notExists(Paths.get(targetFile).getParent())) {
                    Files.createDirectories(Paths.get(targetFile).getParent());
                }

                if (Files.exists(Paths.get(key)) && Files.exists(Paths.get(targetFile))) {
                    Files.copy(Paths.get(key), Paths.get(targetFile), StandardCopyOption.REPLACE_EXISTING);
                }
            }

            result.setSuc(true);

        } catch (Exception e) {
            result.setSuc(false);
            result.setError(e.getMessage());

            e.printStackTrace();
        } finally {
            log.info("----结束replace js[{}]----", result.isSuc());
        }

        if (result.isSuc() == true) {
            return invoker.invoke();
        }

        return result;
    }
}
